﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace Core.GameTool.Framework.Extensions
{
    public static class ObjectExtensions
    {
        public static T To<T>(this object obj) where T : struct
        {
            try
            {
                if (typeof(T) == typeof(Guid))
                {
                    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(obj.ToString());
                }

                if (typeof(T).IsEnum)
                {
                    if (obj is string)
                        obj = obj.To<int>();

                    if (Enum.IsDefined(typeof(T), obj))
                    {
                        return (T)Enum.Parse(typeof(T), obj.ToString());
                    }
                    else
                    {
                        throw new ArgumentException($"Enum type undefined '{obj}'.");
                    }
                }
                return (T)Convert.ChangeType(obj, typeof(T), CultureInfo.InvariantCulture);
            }
            catch
            {
                return default;
            }
        }

        public static string ToJson<T>(this T value)
        {
            var options = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) };
            return JsonSerializer.Serialize(value, options);
        }


    }
}
